//
//  partyPacket.m
//  Wi-Fi Party remade-1
//
//  Created by Vieta Ken on 2021/4/23.
//

#import "partyPacket.h"

@implementation partyPacket

-(id)init:(long)length{
    self=[super init];
    self->send_content=malloc(length+sizeof(struct header));
    self->length=length;
    self->header=(struct header *)self->send_content;
    self->header->version_number=PROTOCOL_VERSION_NUMBER;
    strcpy(self->header->partypacket_string, "partypacket");
    self->self_allocated=true;
    
    return self;
}

-(id)init:(long)length received:(signed char*)buffer{
    self=[super init];
    self->send_content=buffer;
    self->length=length-sizeof(struct header);
    self->header=(struct header*)self->send_content;
    if(strcmp("partypacket", self->header->partypacket_string)!=0){
        NSLog(@"Not a party packet");
        return nil;
    }
    self->self_allocated=false;
    /*{//Byte order
        signed short *payload_addr=(signed short *)[self getPayloadAddr];
        long short_length=self->length/2;
        for(int i=0;i<short_length;i++){
            payload_addr[i]=ntohs(payload_addr[i]);
        }
    }*/
    
    return self;
}

-(void)send:(int)socket toAddr:(struct sockaddr_in *)address{
    /*{//Byte order
        signed short *payload_addr=(signed short *)[self getPayloadAddr];
        long short_length=self->length/2;
        for(int i=0;i<short_length;i++){
            payload_addr[i]=htons(payload_addr[i]);
        }
    }*/
    for(int i=0;i<RESEND;i++){
        sendto(socket, self->send_content, length+sizeof(struct header), 0, (struct sockaddr*)address, sizeof(*address));
    }
}

-(signed char *)getPayloadAddr{
    return self->send_content+sizeof(struct header);
}
-(unsigned long long *)getPacketNumber{
    return &self->header->packet_number;
}
-(long)getLength{
    return self->length;
}
-(void)setNumber:(unsigned long long)packet_number{
    self->header->packet_number=packet_number;
}

-(void)dealloc{
    if(self->self_allocated){
        free(self->send_content);
    }
}

@end
